package com.ty.game.lang;

import com.ty.game.utils.SpringUtil;
import lombok.Getter;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.Closeable;

/**
 * @author: Troy.Chen(失足程序员, 15388152619)
 * @version: 2021-08-20 14:05
 **/
@Getter
public class SqlBatch implements Closeable {

    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;

    public SqlBatch() {
        /*SqlSessionFactory 里面必须包含 mapper 里面的映射*/
        this.sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        this.sqlSession = this.sqlSessionFactory.openSession(ExecutorType.BATCH, false);//
    }

    public void insert(Class<?> daoClass, Object object) {
        this.insert(daoClass.getName(), object);
    }

    public void insert(String daoName, Object object) {
        this.sqlSession.insert(daoName + ".insert", object);
    }

    public void update(Class<?> daoClass, Object object) {
        this.update(daoClass.getName(), object);
    }

    public void update(String daoName, Object object) {
        this.sqlSession.update(daoName + ".update", object);
    }

    /**
     * 提交
     */
    public void commit() {
        sqlSession.commit();
    }

    /**
     * 回滚
     */
    public void rollback() {
        sqlSession.rollback();
    }

    public void close() {
        sqlSession.close();
    }

}